// Copyright (C) 2012 Tanmay Sinha
// All rights reserved

package org.saakshar;

import static org.saakshar.utils.HttpReqestUtils.*;
import static org.saakshar.utils.StringUtils.*;

import org.apache.http.client.methods.HttpGet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

/**
 * 
 * Retrieve a word definition from Wordnik using REST
 * 
 * @author tanmay
 * 
 */
public class WordDefinitionRetriever extends AsyncTask<String, Integer, String> {

	/** The Tag */
	private static final String TAG = WordDefinitionRetriever.class
			.getSimpleName();

	private static final String WORDNIK_WORD_DEFINITION_URL_START = "http://api.wordnik.com/v4/word.json/";
	private static final String WORDNIK_WORD_DEFINITION_URL_END = "/definitions?limit=3";

	private static final String API_KEY = "api_key";

	@Override
	protected String doInBackground(String... params) {

		if ((params.length != 2)
				|| (isBlank(params[0]) || (isBlank(params[1])))) {
			throw new IllegalArgumentException(
					"Retrievel of a word requires both api-key and the word");
		}

		String definition;
		String jsonResponse = getWordDefinitionResponse(params[0], params[1]);

		try {
			JSONArray jsonArray = new JSONArray(jsonResponse);

			StringBuilder stringBuilder = new StringBuilder();

			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				stringBuilder.append("(" + jsonObject.getString("partOfSpeech")
						+ ") ");
				stringBuilder.append(jsonObject.getString("text"));

				if (i < jsonArray.length() - 1) {
					stringBuilder.append("\n\n");
				}
			}

			definition = stringBuilder.toString();

		} catch (JSONException e) {
			definition = null;
			Log.e(TAG, "Failed to parse JSON - " + jsonResponse);
		}

		return definition;
	}

	public String getWordDefinitionResponse(String apiKey, String word) {

		if (!isBlank(word)) {
			String finalUrl = WORDNIK_WORD_DEFINITION_URL_START + word
					+ WORDNIK_WORD_DEFINITION_URL_END;

			HttpGet httpGet = new HttpGet(finalUrl);
			httpGet.setHeader(API_KEY, apiKey);

			return executeGetRequest(httpGet);
		}

		return null;
	}

}
